import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:body_measurement/common/global.dart';
import 'package:body_measurement/common/http_util.dart';
import 'package:body_measurement/models/base_response.dart';
import 'package:body_measurement/models/task_data_source.dart';
import 'package:body_measurement/models/token_info.dart';
import 'package:body_measurement/models/login_result.dart';
import 'package:body_measurement/models/measuring_list_result.dart';

class MeasuringApi {
  final _tokenPath = '/token/get';
  final _loginPath = '/order_admin/index/login';
  final _logoutPath = '/order_admin/index/logout';
  final _taskListPath = '/order_admin/measuring.index/measuring_list';
  static final MeasuringApi _instance = MeasuringApi._internal();

  factory MeasuringApi() => _instance;

  MeasuringApi._internal();

  void getToken() {
    MeyHttpUtil().get(_tokenPath).then((value) async {
      var res = BaseResponse.fromJson(
          json.decode(value.toString()), (jsonT) => TokenInfo.fromJson(jsonT));
      Global.token = res.result.xToken;
    });
  }

  Future<BaseResponse<LoginResult>> login(String username, String password) async {
    var res = await MeyHttpUtil()
        .get(_loginPath, params: {'mobilephone': username, 'password': password});
    return BaseResponse.fromJson(json.decode(res.toString()), (jsonT) {
      if (jsonT is List) {
        if (jsonT.isEmpty) {
          return LoginResult(null);
        }

        throw UnsupportedError('【login】接口错误!');
      }

      return LoginResult.fromJson(jsonT);
    });
  }

  void logout() {
    MeyHttpUtil().get(_logoutPath).then((value) async {
      BaseResponse.fromJson(json.decode(value.toString()), (json) {});
    });
  }

  void getTaskList(TaskDataSource dataSource) {
    debugPrint('53=====');
    MeyHttpUtil().get(_taskListPath).then((value) {
      var res = BaseResponse.fromJson(
          json.decode(value.toString()), (json) => MeasuringListResult.fromJson(json));
      debugPrint('57=====');
      if (res.errcode == 0) {
        debugPrint('59=====');
        dataSource.updateTaskData(res.result.taskList);
      }
    });
  }
}
